package com.gwtprocessingjs.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Random;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;

/**
 * This class demonstrates pushing data from GWT into Processing
 * Javascript code.
 */
public class GwtToJs implements EntryPoint {
	
	// UI Elements.
	private final FlowPanel back = new FlowPanel();
	private final TextBox redInput = new TextBox();
	private final TextBox greenInput = new TextBox();
	private final TextBox blueInput = new TextBox();
	private final Button setColorButton = new Button("Set Color!");
	
	@Override
	public void onModuleLoad() {
		initializeCanvas();
		RootPanel.get("gwt").add(back);
		HorizontalPanel hp = new HorizontalPanel();
		back.add(hp);
		hp.add(redInput);
		hp.add(greenInput);
		hp.add(blueInput);
		hp.add(setColorButton);
		back.add(new Label("Pushing data from GWT controls int the processing JS script"));

		redInput.setWidth("50px");
		greenInput.setWidth("50px");
		blueInput.setWidth("50px");
		redInput.setText(String.valueOf(Random.nextInt(255)));
		greenInput.setText(String.valueOf(Random.nextInt(255)));
		blueInput.setText(String.valueOf(Random.nextInt(255)));
		
		setColorButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				int r, g, b = 0;
				try {
					r = Integer.parseInt(redInput.getText());
					g = Integer.parseInt(greenInput.getText());
					b = Integer.parseInt(blueInput.getText());
				} catch (NumberFormatException e) {
					r = g = b = 0;
					redInput.setText("0");
					greenInput.setText("0");
					blueInput.setText("0");
				}
				setColor(r, g, b);
			}
		});
	}
	
	// --- Private Methods ---
	
	/**
	 * Initialize a Processing instance and associate it with the
	 * canvas defined in the HTML.
	 */
	private native void initializeCanvas() /*-{
		$wnd.initializeCanvas();
	}-*/;
	
	/**
	 * Set the color of the ball by calling a method in the Processing
	 * Javascript code.
	 * @param r red value between 0 and 255
	 * @param g green value between 0 and 255
	 * @param b blue value between 0 and 255
	 */
	private native void setColor(int r, int g, int b) /*-{
		$wnd.setColor(r, g, b);
	}-*/;
}
